// xc_lshop/shop/user/vip/center.js
var app = getApp();
var actmember = require('../../../../xc/model/member')
var actcouponbill = require('../../../../xc/model/coupon_cont')

Page({
  mixins: [require('../../../../xc/mixins/basicMixin')],

  /**
   * 页面的初始数据
   */
  data: {
    basicurl: -1,
    bannercur: 0,
    banner: [{
        background: "#D3D3D3",
        imgurl: "https://img.yzcdn.cn/vant/cat.jpeg",
      },
      {
        background: "#F0D6B4",
        imgurl: "https://img.yzcdn.cn/vant/cat.jpeg",
      },
      {
        background: "#E4CDC2",
        imgurl: "https://img.yzcdn.cn/vant/cat.jpeg",
      }
    ],
    authlist: [{
        imgurl: 'eq/images/vip/auth1.png',
        name: "会员优惠券"
      },
      {
        imgurl: 'eq/images/vip/auth2.png',
        name: "全场打折"
      }, {
        imgurl: 'eq/images/vip/auth3.png',
        name: "生日福利"
      }, {
        imgurl: 'eq/images/vip/auth4.png',
        name: "购物专区"
      }
    ],
    form: {
      name: ""
    },
    calendarshow: false,
    minDate: new Date(1950, 0, 1).getTime(),
    currentDate: new Date(1990, 0, 1).getTime(),
    maxDate: new Date().getTime(),
    gradecoupons: null,
    birthcoupons:null
  },

  xcloaddata: function (options, config) {

    this.setconfig(config)
  },
  receivecoupon(ev) {
    var dataset = ev.currentTarget.dataset;
    var item = dataset.item
    var idx = dataset.idx
    var objname = dataset.obj

    var that = this
    var app = getApp();

    app.xc_sys_config.authop.oppower("login").then(function (res) {

      actcouponbill.receivecoupon(item.id).then(res => {
        var updatemodel = {}
        var keyval = objname + "[" + idx + "]."
        if (res["status"] == 1) {
          updatemodel[keyval + "myreceivednum"] = res["obj"].myreceivednum
          updatemodel[keyval + "receivednum"] = res["obj"].receivednum


          that.setData(updatemodel)

          wx.showToast({
            title: '领取成功',
          })
        } else {
          if (res["status"] == -1) {
            wx.showModal({
              title: '错误',
              content:res["message"]?res["message"]:'领取失败',
            })
          } else if (res["status"] == 2) {
            updatemodel[keyval + "receivednum"] = this.data.modellist[idx].num;
            that.setData(updatemodel)
          } else if (res["status"] == 3) {
            updatemodel[keyval + "myreceivednum"] = this.data.modellist[idx].everyonelimit
            that.setData(updatemodel)
          }

        }

      })


    })





  },
  setconfig(config) {
    if (config.vip) {
      if (config.vip.status == 1) {
        var update = {}
        var rank = config.vip.rank;
       
        update['viprank'] = rank
    
      
        update['message'] = config.vip.contcont;
        update['banner'] = rank
        if (config.payment) {
          update['paymentconfig'] = config.payment;
        }

        this.setData(update)
      } else {
        this.error("会员功能未开启", true)
      }
    } else {
      this.error("会员功能未配置", true)
    }



  },
  setconfig1(config) {
    if (config.vip) {
      if (config.vip.status == 1) {
        var update = {}
        var rank = config.vip.rank;
        update['viprank'] = rank
        var banner = [];
        var expnum=0
        for (var i in rank) {
          var upmoney = rank[i].needexp * rank[i].changemoney;
          expnum +=rank[i]['needexp'] * 1;
          var newitem = {
            changemoney:rank[i].changemoney,
            upmoney: upmoney,
            isupgrade: rank[i * 1 + 1] ? rank[i * 1 + 1] : '',
            name: rank[i]['name'],
            rankmoney: rank[i]['rankmoney'],
            bg: rank[i]['cssbg'],
            maincolor: rank[i]['maincolor'],
            level: rank[i]['level'],
            needexp: expnum
          }
          banner.push(newitem)
        }
        update['message'] = config.vip.contcont;
        update['banner'] = banner
        if (config.payment) {
          update['paymentconfig'] = config.payment;
        
        }

        this.setData(update)
      } else {
        this.error("会员功能未开启", true)
      }
    } else {
      this.error("会员功能未配置", true)
    }



  },

  valide(form) {
    var filed = ['name', 'phone']
    var errormess = {
      'name': '请输入您的姓名;',
      'phone': '请授权您的手机号;'
    }
    var status = true;
    var message = "";
    for (var i in filed) {
      if (!form[filed[i]]) {
        status = false;
        message = message + errormess[filed[i]] + ""
      }
    }
    if (message) {
      wx.showModal({
        title: "错误",
        content: message
      })
    }
    return status;
  },
  openVip() {
    var that = this;
    var formdata = this.data.form
    var status = this.valide(formdata);
    if (status) {
      app.xc_sys_config.authop.oppower("login").then(function (res) {
        if (res['status'] == 1) {
          actmember.regvip(formdata).then(function (res) {
            if (res["status"] == 1) {
              var updatemodel = {};
              updatemodel["member.memberinfo.isvip"] = 1
              updatemodel["member.memberinfo.vipinfo"] = res["obj"]
              app.globalData.member.memberinfo["isvip"] = 1
              app.globalData.member.memberinfo["vipinfo"] = res["obj"]
              // console.log("ppppppppppppppppppppppppppsssssssssssssssssssssssssss")
              // console.log( res["obj"])

              // console.log(app.globalData.member)

              that.setData(updatemodel)
              that.aftergetuserinfo(that.data.member)
              wx.showToast({
                icon: "none",
                title: '开通成功',
              })
            } else {
              wx.showToast({
                icon: "error",
                title: '开通失败',
              })
            }
          })
        }
      })
    }
  },
  //已登入传参数
  afterlogin: function (options, config, userinfo) {
    var that = this;

    that.setData({
      "member": userinfo
    })
    this.aftergetuserinfo(userinfo)
  },
  //登入或者注册后要变的信息
  aftergetuserinfo(userinfo) {
    if (userinfo.memberinfo) {
      var form = {}
      if (userinfo.memberinfo.name) {
        form['name'] = userinfo.memberinfo.name
      }
      if (userinfo.memberinfo.phone) {
        form['phone'] = userinfo.memberinfo.phone
      }
      if (userinfo.memberinfo.birthday) {
        form['birth'] = userinfo.memberinfo.birthday
      }

      this.setData({
        form: form
      })

      if (userinfo.memberinfo.vipinfo) {
        var grade=userinfo.memberinfo.vipinfo.index;
        this.setData({
          grade:grade
        })
        this.getcoupon(grade)
        if (userinfo.memberinfo.birthday) {
         
          var birth = new Date(userinfo.memberinfo.birthday);
          var birthmonth = birth.getMonth();
          var birthdate = birth.getDate();
          var nowdates = new Date();
          var nowmonth = nowdates.getMonth();
          var nowdate = nowdates.getDate();
          // console.log(nowmonth)
          // console.log(birthmonth)
          // console.log(birthdate)
          // console.log(nowdate)

          if (nowmonth == birthmonth && birthdate == nowdate) {
            this.getbirthcoupon(grade)
          }
        }
        this.getpagelist(this,1)
        
      }
    }
  },
  //获取等级专用活动产品
  getpagelist(that, rest, strwhere) {
    if (rest == 1) {
      if (!strwhere) {
        strwhere = {};
      }

      strwhere["grade"] = that.data.grade;
      that.setData({ modellist: [] });
    }
    actmember.gradeoffset(that, rest, strwhere).then(function (result) {
      console.log("rsult")

      console.log(result)
      var updatemdoel = {};

      if ((result["code"] == "over" && result["obj"]) || result["code"] == "loadmore") {

        //  for(var a in result["obj"]["modellist"] ){
        //    if(result["obj"]["modellist"][a]){
        //     result["obj"]["modellist"][a]["snapshot"] = JSON.parse(result["obj"]["modellist"][a]["snapshot"])
        //    }
        //  }     
        if (rest == 1) {
          updatemdoel["modellist"] = result["obj"]["modellist"];
        }
        else {
          if (result["obj"]["modellist"].length > 0) {
            updatemdoel["modellist"] = that.data.modellist.concat(result["obj"]["modellist"]);
          }
        }
      }
      wx.stopPullDownRefresh();
      console.log("updatemdoel")
      console.log(updatemdoel)
      that.setData(updatemdoel);
     

    });
  },
  
  // getgradepro(grade) {
  //   var that = this
    
  //   actmember.getgradepro(grade).then(function (res) {
  //     if (res["status"] == 1) {
  //       console.log(res['obj'])
  //       that.setData({
  //         birthcoupons: res['obj']
  //       })
  //     }
  //   })
  // },
  //生日优惠券
  getbirthcoupon(grade) {
    var that = this
    var condition = {
      "category": 4,
      grade:grade
    }
    actmember.getcoupon(condition).then(function (res) {
      if (res["status"] == 1) {
        console.log(res['obj'])
        that.setData({
          birthcoupons: res['obj']
        })
      }
    })
  },
  //会员登记优惠券
  getcoupon(grade) {
    var that = this
    var condition = {
      "category": 8,
      grade: grade
    }

    actmember.getcoupon(condition).then(function (res) {
      if (res["status"] == 1) {
        console.log(res['obj'])
        that.setData({
          gradecoupons: res['obj']
        })
      }
    })
  },
  // 登录注册
  login(e) {
    var that = this;
    if (e.currentTarget.dataset.status == -1) {
      app.xc_sys_config.authop.oppower("login").then(function (res) {
        that.setData({
          "member": app.globalData.member
        })
        that.updatesimplevipinfo();
        that.aftergetuserinfo(app.globalData.member)
      })
    }
  },
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {

  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
     if(this.data.member){
      this.aftergetuserinfo(this.data.member)
     }
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    this.getpagelist(this,-1)
  },
  //获取手机号码
  getPhoneNumber(e) {
    var that = this;
    var dataset = e.currentTarget.dataset;
    var encryptedData = e.detail.encryptedData;
    // if (!encryptedData) {
    //   return;
    // }
    var iv = e.detail.iv;
    var code = e.detail.code;

    var app = getApp();
    app.toolv2.getphone(encryptedData, iv,code).then(function (data) {
      if (data["code"] == "success") {
        var upatemodel = {};
        upatemodel["form.phone"] = data["obj"].phoneNumber;
        that.setData(upatemodel)
      }
    });
  },
  //input输入
  oninputChange(e) {
    var filed = e.currentTarget.dataset.filed;
    var name = "form." + filed
    this.setData({
      [name]: e.detail
    })
  },
  // banner
  bannerchange(e) {
    var cur = e.detail.current;
    this.setData({
      bannercur: cur
    })
  },
  //------选择生日---start------
  chooseBirth(e) {
    this.setData({
      calendarshow: true
    })
  },
  formatDate(date) {
    date = new Date(date);
    return `${date.getFullYear()}-${this.changenum(date.getMonth() + 1)}-${this.changenum(date.getDate())}`;
  },
  changenum(num) {
    if (num < 10) {
      num = "0" + num
    }
    return num
  },
  onCalendarConfirm(e) {
    var val = e.detail;
    this.setData({
      'form.birthday': `${this.formatDate(val)}`,
    })
    this.onCalendarClose()
  },
  onCalendarClose() {
    this.setData({
      calendarshow: false
    })
  },
  //------选择生日---end------
})